package cvo.chess.client.entities.armies.pieces;

import java.util.ArrayList;
import java.util.List;

import cvo.chess.client.entities.IGameFacade;
import cvo.chess.client.entities.chessboard.ChessboardCoordinate;
import cvo.chess.client.entities.chessboard.IChessboardCoordinate;
import cvo.chess.client.entities.game.Army;
import cvo.chess.client.entities.game.Piece;

public class Bishop extends Piece {

	public Bishop(IGameFacade gf, Army army) {
		super(gf, army);
	}

	public Bishop(IGameFacade gf, Army army, String name) {
		super(gf, army, name);
	}

	@Override
	public List<ChessboardCoordinate> getPossibleMoves() throws Exception {
		List<ChessboardCoordinate> all = new ArrayList<ChessboardCoordinate>();
		all.addAll(iterateDirection(-1, -1));
		all.addAll(iterateDirection(-1, +1));
		all.addAll(iterateDirection(+1, -1));
		all.addAll(iterateDirection(+1, +1));
		return all;
	}

	private boolean isEnemy(ChessboardCoordinate position) {
		return gf.getPieceAt(position).getColor().equals(this.getColor());
	}

	private boolean isEmptyPosition(ChessboardCoordinate position) {
		return (gf.getPieceAt(position) == null);
	}

	private boolean isOnBoard(ChessboardCoordinate position) {
		return position.getCol() < gf.getBoard().getWidth()
				&& position.getRow() < gf.getBoard().getHeight();
	}

	private List<ChessboardCoordinate> iterateDirection(int xMove, int yMove) throws Exception {
		List<ChessboardCoordinate> possibleMoves = new ArrayList<ChessboardCoordinate>();
		IChessboardCoordinate currentPosition = gf.getPositionOfPiece(this);
		ChessboardCoordinate possiblePosition;

		int x = currentPosition.getCol() + xMove;
		int y = currentPosition.getRow() + yMove;

		do {
			possiblePosition = new ChessboardCoordinate(gf.getBoard(), x, y);
			possibleMoves.add(possiblePosition);
			x = x + xMove;
			y = y + yMove;
		} while (isEmptyPosition(possiblePosition)
				&& isOnBoard(possiblePosition));

		if (isOnBoard(possiblePosition) && isEnemy(possiblePosition)) {
			possibleMoves.add(possiblePosition);
		}
		return possibleMoves;
	}
}
